<template>
  <div class="container">
    <div class="weui_cells_title">诊疗号：</div>
    <div class="weui_cells weui_cells_access" style="margin-top:10px;">
      <a @click="selectCard" class="weui_cell" href="javascript:;">
        <div class="weui_cell_hd">
          <i class="fa fa-credit-card fa-2x icon-color" style="width:45px;margin-right:5px;display:block;"></i>
        </div>
        <div class="weui_cell_bd weui_cell_primary">
          <p>{{card?card.name:''}}</p>
          <p>{{card?card.num:''}}</p>
        </div>
        <div class="weui_cell_ft">
          选诊疗号
        </div>
      </a>
    </div>
    <div>
      <div class="weui_cells_title">
        <p class="am-ft-sm am-ft-gray">
          <span class="am-ft-orange"><i class="fa fa-info-circle"></i></span> 只支持查询预约日期起15日内的预约
        </p>
      </div>
      <div class="weui_cells weui_cells_access weui_cells_form">
        <div class="weui_cell">
          <div class="weui_cell_hd">
            <label class="weui_label">预约日期</label>
          </div>
          <div class="weui_cell_bd weui_cell_primary">
            <input class="weui_input" type="date" v-model="startDate">
          </div>
          <div class="weui_cell_ft">
          </div>
        </div>
      </div>
    </div>
    <div class="weui_cells_title" v-show="showEmpty">{{emptyMsg}}</div>
    <div class="weui_cells weui_cells_access ft-sm" style="margin-top:10px;">
      <div v-for="bookInfo in bookInfos" class="weui_cell">
        <div class="weui_cell_bd weui_cell_primary">
          <p>科室：<span class="am-ft-sm am-ft-blue">{{bookInfo.deptName}}</span></p>
          <p>医生：<span class="am-ft-sm am-ft-blue">{{bookInfo.doctorName}}</span></p>
          <p>挂号类型：<span class="am-ft-sm am-ft-blue">{{bookInfo.regType}}</span></p>
          <p>预约就诊时间：<span class="am-ft-sm am-ft-blue">{{bookInfo.bookStartTime.substr(0,10)}} {{bookInfo.bookStartTime.substr(11,5)}} - {{bookInfo.bookEndTime.substr(11,5)}}</span></p>
          <p>状态：<span class="am-ft-sm am-ft-blue">{{bookInfo.state}}</span></p>
          <p>预约创建时间：<span class="am-ft-sm am-ft-blue">{{bookInfo.bookTime}}</span></p>
        </div>
        <div class="weui_cell_hd">
          <p v-show="bookInfo.canCancelBook">
            <a @click="cancelBook($index)" href="javascript:;" class="weui_btn weui_btn_mini weui_btn_warn">取消预约</a>
          </p>
<!--           <p>&nbsp;</p>
          <p v-show="bookInfo.canCheckIn">
            <a @click="checkIn($index)" href="javascript:;" class="weui_btn weui_btn_mini weui_btn_primary">报&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;到</a>
          </p> -->
        </div>
      </div>
    </div>
    <partial name="footer-copyright"></partial>
  </div>
</template>
<style scoped>
.ft-sm p {
  padding: 3px;
  font-size: 12px;
}

.blue_tag {
  background-color: #0ae;
  color: #fff;
  font-size: 13px;
  padding: 2px 4px;
  border: none;
  vertical-align: middle;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}

.orange_tag {
  background-color: #ff8208;
  color: #fff;
  font-size: 13px;
  padding: 2px 4px;
  border: none;
  vertical-align: middle;
  -moz-border-radius: 3px;
  -webkit-border-radius: 3px;
  border-radius: 3px;
}
</style>
<script>
/*global WeixinJSBridge*/

import { commonUtil } from '../../plugins/common'
import {
  showConfirm,
  showCommonToast,
  hideCommonToast,
  showLoadingToast,
  hideLoadingToast
} from '../../vuex/actions'
import _ from 'underscore'

export default {
  name: 'SearchBookInfoView',
  data: function () {
    return {
      startDate: '',
      bookInfos: [],
      regOrderId: -1,
      showEmpty: false,
      emptyMsg: ''
    }
  },
  vuex: {
    getters: {
      card: ({ card }) => _.findWhere(card.cards, { isSelected: true })
    },
    actions: {
      showConfirm,
      showCommonToast,
      hideCommonToast,
      showLoadingToast,
      hideLoadingToast
    }
  },
  ready: function () {
    this.startDate = commonUtil.getDateStr(-7)

    this.$watch('startDate', function (val) {
      this.getBookInfos()
    })

    this.$watch('card', function (val) {
      this.getBookInfos()
    })

    this.getBookInfos()
  },
  methods: {
    selectCard: function () {
      this.$router.go({ name: 'selectCard' })
    },
    getBookInfos: function () {
      if (!this.card || this.startDate === '') {
        return
      }
      this.showEmpty = false

      var self = this

      this.$ajax.get('GetBookInfo', 'Book', {
        cardNo: this.card.num,
        startDate: this.startDate
      }).then(function (data) {
        if (data.ResultCode !== '0') {
          self.showEmpty = true
          self.emptyMsg = data.ResultMsg
          self.bookInfos = []
        } else {
          self.bookInfos = _.map(data.BookInfos, function (val) {
            return {
              flowNo: val.FlowNo,
              bookNo: val.BookNo,
              deptName: val.DeptName,
              doctorName: val.DoctorName,
              regType: val.RegType,
              bookStartTime: val.BookStartTime,
              bookEndTime: val.BookEndTime,
              bookTime: val.BookTime,
              state: val.State,
              canCancelBook: val.CanCancelBook,
              canCheckIn: val.CanCheckIn
            }
          })

          if (self.bookInfos.length <= 0) {
            self.showEmpty = true
            self.emptyMsg = '找不到预约记录'
            self.bookInfos = []
          }
        }
      })
    },
    cancelBook: function (idx) {
      var bookInfo = this.bookInfos[idx]
      var self = this

      this.showConfirm({
        title: '请确认',
        msg: '您确定要取消预约吗？'
      }).then(function (clickedBtn) {
        if (clickedBtn === 'yes') {
          self.doCancelBook(bookInfo.flowNo)
        }
      })
    },
    doCancelBook: function (flowNo) {
      var self = this
      this.showLoadingToast({ msg: '正在取消预约...' }, false)

      this.$ajax.get('CancelBook', 'Book', { flowNo: flowNo }).then(function (data) {
        if (data.ResultCode !== '0') {
          self.hideLoadingToast()
          self.showCommonToast({ msg: data.ResultMsg })
          return
        }
        self.getBookInfos()
      })
    },
    checkIn: function (idx) {
      var bookInfo = this.bookInfos[idx]
      var self = this

      this.showConfirm({
        title: '请确认',
        msg: '报到操作将收取挂号费,继续操作？'
      }).then(function (clickedBtn) {
        if (clickedBtn === 'yes') {
          self.doCheckIn(bookInfo.flowNo)
        }
      })
    },
    doCheckIn: function (flowNo) {
      var self = this
      this.showLoadingToast({ msg: '正在报到...' }, false)

      this.$ajax.get('CreateRegOrder', 'Book', {
        flowNo: flowNo
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.hideLoadingToast()
          self.showCommonToast({ msg: data.ResultMsg })
          return
        } else {
          self.regOrderId = data.OrderId
          self.callPay(data.PayString)
        }
      })
    },
    callPay: function (payString) {
      var self = this
      if (payString === '') {
        this.paySucceed()
        return
      }
      WeixinJSBridge.invoke('getBrandWCPayRequest', JSON.parse(payString), function (res) {
        // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
        // 因此微信团队建议，当收到ok返回时，向商户后台询问是否收到交易成功的通知，若收到通知，前端展示交易成功的界面；
        // 若此时未收到通知，商户后台主动调用查询订单接口，查询订单的当前状态，并反馈给前端展示相应的界面。
        if (res.err_msg === 'get_brand_wcpay_request:ok') {
          self.paySucceed()
        } else {
          console.log(res)
          self.payFailed()
        }
      })
    },
    payFailed: function () {
      this.$ajax.get('PayFailed', 'Reg', {
        orderId: this.regOrderId
      }, false).then(function (data) {

      })

      this.hideLoadingToast()

      this.showCommonToast({ msg: '您已取消支付' })
      window.history.go(-1)
    },
    paySucceed: function () {
      var self = this
      this.$ajax.get('GetRegStatus', 'Reg', {
        orderId: this.regOrderId
      }, false).then(function (data) {
        if (data.ResultCode !== '0') {
          self.hideLoadingToast()
          window.history.go(-1)
        } else {
          if (data.RegStatus === '1') {
            self.hideLoadingToast()
            self.showCommonToast({ msg: data.ResultMsg })
          } else if (data.RegStatus === '0') {
            self.hideLoadingToast()
            self.showCommonToast({ msg: '报到成功' })
            self.$router.replace({ name: 'regInfoDetail', query: { orderId: self.regOrderId } })
          } else {
            window.setTimeout(function () {
              self.paySucceed()
            }, 500)
          }
        }
      })
    }
  }
}
</script>
